package com.app.lxx.pregnancyberth.widge;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;

import java.util.Locale;

/**
 * Created by Lxx on 2019/4/16.
 * 中文朗读
 */
public class ChineseToSpeech {
    private Context context;
    private TextToSpeech textToSpeech;

    public ChineseToSpeech(Context cont) {
        context = cont;
        //实例化自带语音对象
        textToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    //判断是否支持下面语言
                    int result0 = textToSpeech.setLanguage(Locale.CHINA);
                    int result1 = textToSpeech.setLanguage(Locale.US);
                    int result2 = textToSpeech.setLanguage(Locale.SIMPLIFIED_CHINESE);
                    boolean b0 = result0 == TextToSpeech.LANG_MISSING_DATA || result0 == TextToSpeech.LANG_NOT_SUPPORTED;
                    boolean b1 = result1 == TextToSpeech.LANG_MISSING_DATA || result1 == TextToSpeech.LANG_NOT_SUPPORTED;
                    boolean b2 = result2 == TextToSpeech.LANG_MISSING_DATA || result2 == TextToSpeech.LANG_NOT_SUPPORTED;
                    if (b0 || b1 || b2) {
                        Toast.makeText(context, "不支持朗读功能", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(context, "不支持朗读功能 需要安装TTS插件", Toast.LENGTH_SHORT).show();
//                    Toast.makeText(context, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void speech(String text) {
        // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        textToSpeech.setPitch(1.0f);
        // 设置语速
        textToSpeech.setSpeechRate(1.0f);
        //输入中文，若不支持的设备则不会读出来
        textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }

    public void destroy() {
        if (textToSpeech != null) {
            // 不管是否正在朗读TTS都被打断
            textToSpeech.stop();
            // 关闭，释放资源
            textToSpeech.shutdown();
        }
    }

}
